import pandas as pd
from sklearn.metrics import accuracy_score, roc_curve, auc
import joblib
import matplotlib.pyplot as plt
from util.commonUtil import mean_absolute_percentage_error
from sklearn.metrics import roc_auc_score
import transform_test


def log_predict():
    # 读取数据
    x_test, y_test = transform_test.tes1_do()

    # 逻辑模型预测
    x_test_log = x_test.copy()
    x_test_log.drop(columns=['Age', 'MonthlyIncome', 'TotalWorkingYears', 'DistanceFromHome'], inplace=True)
    src = joblib.load('../model/src.pkl')
    x_test_log = src.transform(x_test_log)

    model_lr = joblib.load('../model/lr.pkl')
    # 预测类别（用于准确率）
    y_pred_log = model_lr.predict(x_test_log)
    # 预测概率(用于 ROC AUC)
    y_pred_proba_log = model_lr.predict_proba(x_test_log)[:, 1]
    auc = roc_auc_score(y_test, y_pred_proba_log)
    accuracy = accuracy_score(y_test, y_pred_log)

    print(f'逻辑回归预测值: {y_pred_proba_log}')
    print(f'逻辑回归AUC值: {auc:.4f}')
    print(f'逻辑回归准确率: {accuracy:.4f}')

    # === 绘制 ROC 曲线 ===
    fpr, tpr, _ = roc_curve(y_test, y_pred_proba_log)
    plt.figure(figsize=(7, 6))
    plt.plot(fpr, tpr, color='darkorange', lw=2, label=f'ROC Curve (AUC = {auc:.4f})')
    plt.plot([0, 1], [0, 1], color='navy', lw=1.5, linestyle='--', label='Random Classifier')
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate (FPR)')
    plt.ylabel('True Positive Rate (TPR)')
    plt.title('ROC Curve - Logistic Regression')
    plt.legend(loc="lower right")
    plt.grid(alpha=0.3)
    plt.tight_layout()

    # 保存 + 显示
    plt.savefig('../data/fig/lr_roc_curve.png', dpi=300)
    plt.show()

if __name__ == '__main__':
    log_predict()
